package com.wx.controller;


import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.eova.common.utils.xx;
import com.eova.interceptor.AuthInterceptor;
import com.eova.interceptor.LoginInterceptor;
import com.jfinal.aop.Before;
import com.jfinal.aop.Clear;
import com.jfinal.kit.PropKit;
import com.jfinal.log.Log;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.weixin.sdk.api.ApiConfigKit;
import com.jfinal.weixin.sdk.api.ApiResult;
import com.jfinal.weixin.sdk.api.MenuApi;
import com.jfinal.weixin.sdk.api.SnsAccessToken;
import com.jfinal.weixin.sdk.api.SnsAccessTokenApi;
import com.jfinal.weixin.sdk.api.SnsApi;
import com.wx.interceptor.JSSDKInterceptor;
import com.wx.model.User;
import com.wx.service.AccountService;
import com.wx.service.UsersService;
import com.wx.util.CharUtil;
import com.xiaoleilu.hutool.util.StrUtil;
/**
 * @author Javen
 * 2015年12月5日下午2:20:44
 *
 */
@Clear({LoginInterceptor.class,AuthInterceptor.class})
public class WeiXinOauthController extends ApiController{
	
	static final UsersService usersService = UsersService.me;
	static final AccountService accountService = AccountService.me;
	static Log log = Log.getLog(WeiXinOauthController.class);
	public void checkUrl(){
		Map m = this.getParaMap();
		log.info(m.toString());
		
//		
		log.info(getPara("backUrl")+"&a="+getPara("a")+"&appid="+getPara("appid")+"&code="+getPara("code")+"&state="+getPara("state"));
		if(StrUtil.isBlank(getPara("a"))){
			redirect(getPara("backUrl")+"?appid="+getPara("appid")+"&code="+getPara("code")+"&state="+getPara("state"));
		}else{
			redirect(getPara("backUrl")+"&a="+getPara("a")+"&appid="+getPara("appid")+"&code="+getPara("code")+"&state="+getPara("state"));
		}
		


	}
	//跳转到授权页面
	public void toOauth(){
		String toUrl = getPara("TOURL");
		String apptype =getPara("apptype");
//		http://www.abc.com/xxx/get-weixin-code.html?appid=XXXX&scope=snsapi_base&state=hello-world&redirect_uri=http%3A%2F%2Fwww.xyz.com%2Fhello-world.html
//		String calbackUrl=xx.getConfig("domain")+"/oauth?appid="+getSessionAttr("appid");
		String calbackUrl=xx.getConfig("domain2")+"?apptype ="+apptype+"&appid="+getSessionAttr("appid")+"&backUrl="+xx.getConfig("domain")+"/oauth";
//		String url=SnsAccessTokenApi.getAuthorizeURL(xx.getConfig("appId"), calbackUrl, toUrl,false);
		String url=SnsAccessTokenApi.getAuthorizeURL(ApiConfigKit.getAppId(), URLEncoder.encode(calbackUrl), toUrl,false);
		redirect(url);
	}
	
	@Before(JSSDKInterceptor.class)
	public void index() {
		int  subscribe=0;
		//用户同意授权，获取code
		String code=getPara("code");
		String state=getPara("state");
		if (code!=null) {
			String appId=ApiConfigKit.getApiConfig().getAppId();
			String appIds=ApiConfigKit.getAppId();
			String secret=ApiConfigKit.getApiConfig().getAppSecret();
			//通过code换取网页授权access_token
			SnsAccessToken snsAccessToken=SnsAccessTokenApi.getSnsAccessToken(appId,secret,code);
//			String json=snsAccessToken.getJson();
			String token=snsAccessToken.getAccessToken();
			String openId=snsAccessToken.getOpenid();
			//拉取用户信息(需scope为 snsapi_userinfo)
			ApiResult apiResult=SnsApi.getUserInfo(token, openId);
			log.warn("getUserInfo:"+apiResult.getJson());
			if (apiResult.isSucceed()) {
				JSONObject jsonObject=JSON.parseObject(apiResult.getJson());
				String nickName=jsonObject.getString("nickname");
				//用户的性别，值为1时是男性，值为2时是女性，值为0时是未知
				int sex=jsonObject.getIntValue("sex");
				String city=jsonObject.getString("city");//城市
				String province=jsonObject.getString("province");//省份
				String country=jsonObject.getString("country");//国家
				String headimgurl=jsonObject.getString("headimgurl");
				String unionid=jsonObject.getString("unionid");
				//获取用户信息判断是否已存在
				List<User> userList = usersService.getUsersByOpenId(openId);
				User user = new User();
				if(userList.size()<1){
					user.setCity(city);
					user.setCountry(country);
					user.setHeadimgurl(headimgurl);
					user.setNickName(CharUtil.removeFourChar(nickName));
					user.setOpenId(openId);
					user.setProvince(province);
					user.setSex(sex);
					user.setSubscribeTime(new Date());
					user.setAppid(appId);
					user.save();
				}else{
					user = userList.get(0);
				}
				setSessionAttr("USER", user);
				setAttr("USER", user);
				//根据APPID获取跳转路径
				
				if (state.equals("2222")) {
					redirect("http://www.cnblogs.com/zyw-205520/");
				}
				else if (state.equals("SERHIS")) {
					renderTemplate("/wx/search.html");
				}else {
					renderTemplate("/wx/index.html");
				}
			}else{
				redirect(xx.getConfig("domain")+"/oauth/toOauth?appid="+appId);
			}
		}else {
			renderText("code is  null");
		}
	}
	
	/**
	 * PC扫码登陆回调 
	 * 获取AccessToken以及用户信息跟微信公众号授权用户用户信息一样
	 */
	public void webCallBack() {
		//用户同意授权，获取code
		String code=getPara("code");
		String state=getPara("state");
		if (code!=null) {
			System.out.println("code>"+code+" state>"+state);
			String appId=PropKit.get("webAppId");
			String secret=PropKit.get("webAppSecret");
			//通过code换取网页授权access_token
			SnsAccessToken snsAccessToken=SnsAccessTokenApi.getSnsAccessToken(appId,secret,code);
			String json=snsAccessToken.getJson();
			System.out.println("通过code获取access_token>>"+json);			
			String token=snsAccessToken.getAccessToken();
			String openId=snsAccessToken.getOpenid();
			//拉取用户信息(需scope为 snsapi_userinfo)
			ApiResult apiResult=SnsApi.getUserInfo(token, openId);
			log.warn("getUserInfo:"+apiResult.getJson());
			if (apiResult.isSucceed()) {
				JSONObject jsonObject=JSON.parseObject(apiResult.getJson());
				String nickName=jsonObject.getString("nickname");
				//用户的性别，值为1时是男性，值为2时是女性，值为0时是未知
				int sex=jsonObject.getIntValue("sex");
				String city=jsonObject.getString("city");//城市
				String province=jsonObject.getString("province");//省份
				String country=jsonObject.getString("country");//国家
				String headimgurl=jsonObject.getString("headimgurl");
				String unionid=jsonObject.getString("unionid");
			}
			renderText("通过code获取access_token>>"+json+"  \n"+"getUserInfo:"+apiResult.getJson());
		}
		
	}
	/**
	 * 获取公众号菜单
	 */
	public void getMenu() {
		ApiResult apiResult = MenuApi.getMenu();
		if (apiResult.isSucceed())
			renderText(apiResult.getJson());
		else
			renderText(apiResult.getErrorMsg());
	}
	
	public void getProCity() {
		List<Record> rList = Db.find("select dp.PROVINCE_NAME,dp.PROVINCE_ID from d_province dp where dp.COMPANY_ID='cb533b4d107211e79eee5254000c718e' and dp.PROVINCE_ID ='48266A6C573511E790E15254000C718E'");
		StringBuffer sql = new StringBuffer("[");
		String name = "";
		Map map = new HashMap<>();
		JSONArray json= new JSONArray();
		for(Record r :rList){
			Map proMap = new HashMap<>();
			proMap.put("Code", r.get("1"));
			proMap.put("Name", r.get("PROVINCE_NAME"));
			List<Record> cityList = Db.find("select dc.city_id,dc.city_name,1 sort   from d_city dc where dc.PROVINCE_ID = '"+r.get("PROVINCE_ID")+"'");
			List<Map> list = new ArrayList<>();
			for(Record rr :cityList){
				Map map1 = new HashMap<>();
				map1.put("Code", rr.get("1"));
				map1.put("Name", rr.get("city_name"));
				map1.put("sort", 1);
				List<Record> dList = Db.find("select d.DISTRICT_ID,d.DISTRICT_NAME from d_district d where d.CITY_ID='"+rr.getStr("city_id")+"'");
				List<Map> list2 = new ArrayList<>();
				for(Record rrr :dList){
					Map map2 = new HashMap<>();
					map2.put("Code", rrr.get("1"));
					map2.put("Name", rrr.get("DISTRICT_NAME"));
					map2.put("sort", 1);
					list2.add(map2);
				}
				map1.put("level", list2);
				list.add(map1);
			}
			proMap.put("level",list);
			json.add(proMap);
		}
		log.info(json.toJSONString());
//		for(Menu m : menuList){
//			Map<String,Object> map = new HashMap<String,Object>();
//			map.put("id", m.getId());
//			map.put("code", m.getCode());
//			map.put("parentId", m.getParentId());
//			map.put("menuName", m.getMenuName());
//			map.put("menuUrl", m.getMenuUrl());
//			map.put("sortId", m.getSortId());
//			map.put("target", "treeFrame");
//			map.put("isHasMenu", true);
//			jsonArray.add(map);
//		}
//		return jsonArray;
	}
	
	/**
	 * 创建菜单
	 */
	public void createMenu()
	{
		String str = "{\n" +
				"    \"button\": [\n" +
				"        {\n" +
				"            \"name\": \"寄件2\",\n" +
//				"            \"url\": \"http://xgwechat.dilinbao.com/oauth/toOauth?appid=wx3bf19919bcd6fc46\",\n" +
				"            \"url\": "+xx.getConfig("domain")+"/oauth/toOauth?appid=wx3bf19919bcd6fc46\",\n" +
				"            \"type\": \"view\"\n" +
				"        },\n" +
				"        {\n" +
				"            \"name\": \"安全保障\",\n" +
				"            \"key\": \"112\",\n" +
				"\t    \"type\": \"click\"\n" +
				"        },\n" +
				"        {\n" +
				"\t    \"name\": \"查询轨迹\",\n" +
				"\t    \"url\": \"http://m.bajie8.com/footer/cjwt\",\n" +
				"\t    \"type\": \"view\"\n" +
				"        }\n" +
				"    ]\n" +
				"}";
		ApiResult apiResult = MenuApi.createMenu(str);
		if (apiResult.isSucceed())
			renderText(apiResult.getJson());
		else
			renderText(apiResult.getErrorMsg());
	}

	

	
	
}
